package hc.j2me.ui;

import hc.core.ConfigManager;
import hc.core.ContextManager;
import hc.core.EventCenter;
import hc.core.IConstant;
import hc.core.IEventHCListener;
import hc.core.Message;
import hc.core.MsgBuilder;
import hc.core.sip.SIPManager;
import hc.core.util.HCURL;
import hc.core.util.LogManager;
import hc.core.util.MsgNotifier;
import hc.j2me.ScreenClientManager;
import hc.j2me.Starter;
import hc.j2me.item.CanvasMenu;
import hc.j2me.item.Form;
import hc.j2me.util.ImageUtility;
import hc.j2me.util.Jcip;
import hc.j2me.util.SoundUtil;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class ProcessAlert extends Canvas implements Runnable{
	private boolean isDone = false;
	
	public void run() {
//		repaint();
		while(isDone == false){
			repaint();
			try{
				//该值不能为100，要不动画效果出不来
				Thread.sleep(50);//原为10，导致占用资源过多，所以改为50
			}catch (Exception e) {
				
			}
		}
	}

	private Thread t;
	
	public void startThread(){
		t = new Thread(this);
		t.start();
	}
	
	public ProcessAlert() {
		super();
		this.msgdisp = new MsgDisper();
		
//		notify("Press any key to exit");
		
//		setType(AlertType.INFO);
//		setTimeout(Alert.FOREVER);
//		setString(Starter.getUIString("m07"));
//		g = new Gauge(null,false,10,0) ;
//		setIndicator(g);
		
		EventCenter.addListener(new IEventHCListener(){
			boolean isRoot = true;
			public boolean action(final byte[] bs) {
				if(isRoot){
					isRoot = false;
					UIManager.emptyStack();
					SoundUtil.playMIDPStartTone();
				}
				
				String body = Message.getMsgBody(bs, MsgBuilder.INDEX_MSG_DATA);

//				hc.core.L.V=hc.core.L.O?false:LogManager.log("Window data:" + body);
				
				final byte[] colorModeTwoBytes = new byte[2 + MsgBuilder.INDEX_MSG_DATA];
				ScreenClientManager.setColorMode(colorModeTwoBytes, Starter.config.colorBit);
				ScreenClientManager.setRefreshMillSecond(Starter.config.refreshMS);

				if(body.equals(IConstant.NO_CANVAS_MAIN)){					
					//进入远控方式
					HCCtrlGameCanvas.enterRemoteScreen(HCURL.URL_HOME_SCREEN);
				}else{
					//进入主菜单模式
					Jcip.setInstance(new Jcip(body));
					String type = Jcip.getInstance().getString();
					
					Displayable disp = null;
					if(type.equals(HCURL.MENU_PROTOCAL)){
						disp = new CanvasMenu();
					}else if(type.equals(HCURL.FORM_PROTOCAL)){
						disp = new Form();
					}else{
						LogManager.err("Unknow Window:" + type);
					}
					if(disp != null){
						UIManager.pushInAndSwithToNew(disp);//清空旧UI，设为新起点
					}
				}
				t = null;
				return true;
			}

			public byte getEventTag() {
				return MsgBuilder.E_CANVAS_MAIN;
			}});
		
	}
	
	public void connect(){
		isEnabelTouchExit = false;
		final boolean result_startConnectionInit = SIPManager.startConnectionInit();
		isEnabelTouchExit = true;
		
		if(result_startConnectionInit == false){
			LogManager.err(Starter.getUIString("1022"));
			LogManager.info("Network congestion may result in this error.");
			LogManager.info("Sorry, please try after one minute");
			MsgNotifier.getInstance().notifyNewMsg("press or touch to exit.");
			return;
		}else{
			LogManager.info("if not work, press to exit.");
//			ContextManager.setStatus(ContextManager.STATUS_READY_MTU);
//			LogManager.info("Succ connect target");
		}
	}
	
	private boolean isEnabelTouchExit = false;
	public MsgDisper msgdisp;
	
	protected void keyReleased(int keyCode){
		inputAnyKey();	
	}

	private void exit() {
		t = null;
		isDone = true;
		UIManager.exitOrReturn();
	}
	
	protected void pointerReleased(int x, int y){
		inputAnyKey();
	}

	private void inputAnyKey() {
		if(isEnabelTouchExit){
			if(Starter.isServerLineOff){
				Starter.isServerLineOff = false;
				exit();
			}else{
				ContextManager.getContextInstance().shutDown();
			}
		}
	}

	private Graphics notifyG;
	private boolean finishedCanvas = false;
	private int width, height;
	private int fromColorBarR, fromColorBarG;
	private short prcessColorBarHeight = 10;
	private short prcessColorBarWidth = 30, doublePrcessColorBarWidth = 60;
	private int idxProcessColorChange, 
		y_processColorBar_begin, 
		y_processColorBar_end;
    private int processColorMax;
	private short directForward = 1;
    private Image image;
	protected void paint(Graphics g) {
		if(finishedCanvas == false){
			width = getWidth();
			height = getHeight();
			image = Image.createImage(width, height);

			synchronized (ConfigManager.table) {
				ConfigManager.put(ConfigManager.ANTI_ALIAS, IConstant.TRUE);
	            notifyG = image.getGraphics();
	            ConfigManager.put(ConfigManager.ANTI_ALIAS, IConstant.FALSE);
			}
            
            y_processColorBar_begin = height - 16;
            y_processColorBar_end = y_processColorBar_begin + prcessColorBarHeight;
        
			fromColorBarR = 0x00;
			fromColorBarG = 0x80;
			
			final int msgLineHeight = ImageUtility.FontHeight + 2 * 1;
			msgdisp.init(
					msgLineHeight,
					((y_processColorBar_begin - 3) / msgLineHeight), 
					width, notifyG);
			
			notifyG.setFont(ImageUtility.UI_Font);
			notifyG.setColor(ImageUtility.COLOR_TRANS_LAY);
			notifyG.fillRect(0, 0, width, height);
			
			
			notifyG.setColor(fromColorBarR, fromColorBarG, 255);
			for (int i = 0; i < width; i++) {
				notifyG.drawLine(i, y_processColorBar_begin, i, y_processColorBar_end);
			}
			
            int b = 255;
			for (int i = 2*prcessColorBarWidth - 1; i >= prcessColorBarWidth; i--) {
                fromColorBarR += 3;
                b -= 4;
				notifyG.setColor(fromColorBarR, --fromColorBarG, b);
				notifyG.drawLine(i, y_processColorBar_begin, i, y_processColorBar_end);
			}
			
			for (int i = prcessColorBarWidth - 1; i >= 0; i--) {
                fromColorBarR -= 3;
                b += 4;
				notifyG.setColor(fromColorBarR, ++fromColorBarG, b);
				notifyG.drawLine(i, y_processColorBar_begin, i, y_processColorBar_end);
			}
            processColorMax = width - 2 * prcessColorBarWidth - 2;
//			fromColorBarR = 0x00;
//			fromColorBarG = 0x80;
			
			finishedCanvas = true;
		}else{		
			if(idxProcessColorChange >= processColorMax){
				directForward = -1;
			}else if(idxProcessColorChange <= 0){
				directForward = 1;
			}
			
			idxProcessColorChange += directForward;
			
            int nextIdx = idxProcessColorChange - 1;
            if(directForward == 1){
                notifyG.copyArea(nextIdx, y_processColorBar_begin, 
                		doublePrcessColorBarWidth, prcessColorBarHeight, 
                        idxProcessColorChange, y_processColorBar_begin, Graphics.TOP|Graphics.LEFT);
                notifyG.setColor(fromColorBarR, fromColorBarG, 255);
                notifyG.drawLine(nextIdx, y_processColorBar_begin, nextIdx, y_processColorBar_end);
            }else{
                notifyG.copyArea(idxProcessColorChange, y_processColorBar_begin, 
                		doublePrcessColorBarWidth, prcessColorBarHeight, 
                        nextIdx, y_processColorBar_begin, Graphics.TOP|Graphics.LEFT);
                notifyG.setColor(fromColorBarR, fromColorBarG, 255);
                int emptyIdx = nextIdx + 2 * prcessColorBarWidth;
                notifyG.drawLine(emptyIdx, y_processColorBar_begin, emptyIdx, y_processColorBar_end);
            }
    		
    		synchronized (msgdisp) {
    			boolean done;
    			while((done = msgdisp.printNextMsg()) == true){
    			}
    		}

		}
        g.drawImage(image, 0, 0, Graphics.TOP|Graphics.LEFT);
	}

	public void clearInfoArea(){
		synchronized (this) {
			notifyG.setColor(ImageUtility.COLOR_TRANS_LAY);
			notifyG.fillRect(0, 0, width, y_processColorBar_begin - 1);
		}
	}

	protected void sizeChanged(int w, int h) {
		super.sizeChanged(w, h);
		if(isEnabelTouchExit){
			return;
		}
		
		if((ScreenClientManager.getClientWidth() > ScreenClientManager.getClientHeight() && w > h) 
				|| (ScreenClientManager.getClientWidth() < ScreenClientManager.getClientHeight() && w < h)){
			return;
		}
		
		//进行高宽交换
		int swap = Starter.config.width;
		Starter.config.width = Starter.config.height;
		Starter.config.height = swap;
		
		ScreenClientManager.setClientWH(Starter.config.width, Starter.config.height);
	}

}
